using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace JoshuaOneEight.Windows
{
	public class AutoFillTextBox : TextBox
	{
		private char? mLastPressedKey;

		#region AutoFillTextBox Members

		/// <summary>
		/// Gets or sets the list of available values.
		/// </summary>
		public List<string> AvailableValues
		{
			get;
			set;
		}

		#endregion AutoFillTextBox Members

		#region Protected Members

		/// <summary>
		/// Handle the OnGotFocus event of the text box.
		/// </summary>
		/// <param name="e"></param>
		protected override void OnGotFocus( EventArgs e )
		{
			base.OnGotFocus( e );
			SelectionStart = 0;
			SelectionLength = Text.Length;
		}

		/// <summary>
		/// Handle the OnKeyPress event of the text box.
		/// </summary>
		/// <param name="e"></param>
		protected override void OnTextChanged( EventArgs e )
		{
			base.OnTextChanged( e );

			if( AvailableValues != null && mLastPressedKey.HasValue && 
				(char.IsLetterOrDigit( mLastPressedKey.Value ) || 
				 char.IsPunctuation( mLastPressedKey.Value ) ||
				 char.IsWhiteSpace( mLastPressedKey.Value ) ))
			{
				string match = AvailableValues.FirstOrDefault( value => value.StartsWith( Text ) );
				if( !string.IsNullOrEmpty( match ) )
				{
					int index = Text.Length;
					Text = match;
					SelectionStart = index;
					SelectionLength = match.Length;
				}
				mLastPressedKey = null;
			}
		}

		/// <summary>
		/// Handle the OnKeyPress event of the text box.
		/// </summary>
		/// <param name="e"></param>
		protected override void OnKeyPress( KeyPressEventArgs e )
		{
			mLastPressedKey = e.KeyChar;
			base.OnKeyPress( e );
		}

		#endregion Protected Members

	}
}